package com.atguigu.exam;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.Socket;

/**
 * 编写一个服务器和一个客户端

 1)服务器可以读取本地文件内容并能将内容发给请求的客户端
 2)再编写一个可以发请求到服务器,并能从服务器段获取文件内容的客户端
 * @author xbd
 * @create 2021-05-31 17:28
 */
public class ClienProjectTest {
    public void connServer(){
        Socket socket = null;
        InputStream is = null;
//        ByteArrayOutputStream bos = null;
        FileOutputStream fos = null;
        try {
            InetAddress inet = InetAddress.getByName("127.0.0.1");
            socket = new Socket(inet, 8899);
            is = socket.getInputStream();
            fos = new FileOutputStream("a2.jpg");
            byte[] bytes = new byte[20];
//            bos = new ByteArrayOutputStream();
            int len;
            while((len = is.read(bytes)) != -1){
//                bos.write(bytes,0,len);
                fos.write(bytes,0,len);
            }
//            System.out.println(bos.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        new ClienProjectTest().connServer();
    }
}
